package com.acmedcare.framework.exchange.center.core.handler;

import com.acmedcare.framework.exchange.center.core.JmxContainerUtil;
import com.acmedcare.framework.exchange.center.core.exception.PluginNotFoundException;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class PluginHandlerProxy implements MethodInterceptor {

  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
      throws Throwable {
    if (method.getName().equals("invoke")) {
      Request request = (Request) objects[0];

      PluginHandlerMBean handlerMBean = JmxContainerUtil.PluginHandlers
          .get(request.getPluginName());
      if (handlerMBean == null) {
        throw new PluginNotFoundException(
            String.format("插件:%s,尚未找到，请确认插件已经正确加载!", request.getPluginName()));
      }

      return handlerMBean.invoke(request);
    }
    return null;
  }
}
